import { view } from "cc";
import { BasePlatform } from "../../framework/base/BasePlatform";
import { LogMgr } from "../../framework/manager/LogMgr";
export class WechatPlatform implements BasePlatform {

    hasVerify() {
        return false;
    }
    canCare(): boolean {
        return false
    }
    canShowBtnMore() {
        return false
    }

    showBlockAd(args?: any, callback?: Function) {
        let a = this.customAdMap.get(args)
        if (args === 1) {
            a = this.customAdMap.get("home")
        }
        if (a) {
            a.show()
        }
    }
    hideBlockAd(args?: any, callback?: Function) {
        let a = this.customAdMap.get(args)
        if (args === 1) {
            a = this.customAdMap.get("home")
        }
        if (a) {
            a.hide()
        }
    }
    showFloatIconAd(args?: any, callback?: Function) {

    }
    hideFloatIconAd(args?: any, callback?: Function) {
        // throw new Error("Method not implemented.");
    }

    addShortcut(args?: any, callback?: Function) {
        //  throw new Error("Method not implemented.");
    }
    checkShortcut(args?: any, callback?: Function) {
        // throw new Error("Method not implemented.");
    }
    shareImg(callback: Function) {
        // throw new Error("Method not implemented.");
    }
    getUserInfo(callback: Function) {
        if (callback) {
            callback(null, null)
        }

    }
    initNativeAd(args?: string, callback?: Function) {
        // throw new Error("Method not implemented.");
    }
    showNativeAd(args?: string, callback?: Function) {
        //  throw new Error("Method not implemented.");
    }
    showGamePortalAd(args?: any, callback?: Function) {
        LogMgr.getInstance().debug("更多游戏")
    }


    showAlert: boolean = true;
    /*是否有广告**/
    hasAd: boolean = true;
    /**是否有banner */
    hasBanner: boolean = true;
    /**是否有插屏 */
    hasInsertAd: boolean = true;
    /**是否有视频 */
    hasVideoAd: boolean = true;


    private BannerAd = null;

    private BannerAdHight: number = 0

    private customAdMap: Map<string, any> = new Map()


    private sdkVersion: string = "";
    private videoAd: wx.RewardedVideoAd;
    private defaultAd: any = "adunit-e46ad2b73262f9c7";//开心连消
    // private defaultAd: any = "adunit-006e553e31779d06";//消个花朵
    // private videoAd1: any = "adunit-006e553e31779d06";
    // private videoAd2: any = "adunit-006e553e31779d06";
    // private videoAd3: any = "adunit-006e553e31779d06";
    // private videoAd4: any = "adunit-006e553e31779d06";
    // private videoAd5: any = "adunit-006e553e31779d06";
    // private videoAd6: any = "adunit-006e553e31779d06";
    // private videoAd7: any = "adunit-006e553e31779d06";
    // private videoAd8: any = "adunit-006e553e31779d06";
    // private videoAd9: any = "adunit-006e553e31779d06";
    // private videoAd10: any = "adunit-006e553e31779d06";
    // private videoAd11: any = "adunit-006e553e31779d06";
    // private videoAd12: any = "adunit-006e553e31779d06";
    // private videoAd13: any = "adunit-006e553e31779d06";
    // private videoAd14: any = "adunit-006e553e31779d06";
    // private videoAd15: any = "adunit-006e553e31779d06";
    // private videoAd16: any = "adunit-006e553e31779d06";
    // private videoAd17: any = "adunit-006e553e31779d06";
    // private videoAd18: any = "adunit-006e553e31779d06";
    // private videoAd19: any = "adunit-006e553e31779d06";
    initTrack() {

    }


    // var uma = require('./umtrack-wx-game/uma.min');
    // uma.init({
    //     appKey: '6098ef1ac9aacd3bd4cd9080', //由友盟分配的APP_KEY
    //     autoGetOpenid: true, // 是否需要通过友盟后台获取openid或匿名openid，如若需要，请到友盟后台设置appId及secret
    //     debug: true, //是否打开调试模式
    //     uploadUserInfo: true // 自动上传用户信息，设为false取消上传，默认为false
    // })
    youmengTrack(key?: any, abName?: any, groupValue?: any, id?: string) {
        if (!wx.uma) {
            return
        }
        if (abName && groupValue) {
            if (abName == "userA") {
                wx.uma.trackEvent(key, { "userA": groupValue });
            } else if (abName == "userB") {
                wx.uma.trackEvent(key, { "userB": groupValue });
            } else if (abName == "userD") {
                wx.uma.trackEvent(key, { "userD": groupValue });
            }
            else {
                wx.uma.trackEvent(key, { "userC": groupValue });
            }

        } else {
            wx.uma.trackEvent(key); // 友盟统计
        }
    }
    canShare(): boolean {
        return false;
    }
    //游戏圈
    createGameClubButton(rect, callback) {
        // 通过 wx.getSetting 查询用户是否已授权头像昵称信息
        let screenSize = view.getVisibleSize();
        let systemInfo = wx.getSystemInfoSync();
        //当前sdk版本
        let screenWidth = systemInfo.screenWidth;
        let screenHeight = systemInfo.screenHeight;
        // 否则，先通过 wx.createUserInfoButton 接口发起授权
        // let leftPos = (rect.x - (rect.width / 2)) * screenWidth / screenSize.width;
        let leftPos = (rect.x) * screenWidth / screenSize.width;// - (rect.width) / 64
        // let topPos = ((screenSize.height - rect.y) - (rect.height / 2)) * screenHeight / screenSize.height;
        let topPos = ((screenSize.height - rect.y) - (rect.height)) * screenHeight / screenSize.height;
        let trueWidth = rect.width * screenWidth / screenSize.width;
        let trueHeight = rect.height * screenHeight / screenSize.height;
        console.log("systemInfo：", screenSize, screenWidth, screenHeight, leftPos, topPos,trueWidth,trueHeight)
        console.log("否则，先通过 wx.createUserInfoButton 接口发起授权", rect, leftPos, topPos)
        let userInfoButton = wx.createGameClubButton({
            type: 'text',
            text: '',
            icon: 'green',
            style: {
                left: leftPos,
                top: topPos,
                width: trueWidth,
                height: trueHeight,
                lineHeight: 40,
                backgroundColor: '#00000000',
                borderColor: '#00000000',
                borderWidth: 1,
                borderRadius: 4,
                textAlign: 'center',
                fontSize: 16,
                // lineHeight: 16,
            }
        })
        userInfoButton.onTap((res) => {
            if (callback) {
                console.log('进入游戏圈');
                callback();
            }
        });
        return userInfoButton;
    }
    initSdk(args?: any, callback?: Function) {
        let systemInfo = wx.getSystemInfoSync();
        //当前sdk版本
        this.sdkVersion = systemInfo.SDKVersion;
        let screenWidth = systemInfo.screenWidth;
        let screenHeight = systemInfo.screenHeight;
        // 分享版本支持
        if (this.compareVersion(this.sdkVersion, "1.1.0") >= 0) {
            wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            })
            wx.onShareAppMessage(function () {
                return {   
                    title: '不花钱只烧脑，你能过这一关吗?',
                    imageUrl: 'https://i.postimg.cc/xdW0hfJY/20241021172111.jpg'
                }
            })
        }

        // 激励广告版本支持
        if (this.compareVersion(this.sdkVersion, "2.0.4") >= 0) {
            // this.videoAd1 = wx.createRewardedVideoAd({ adUnitId: "adunit-70dc1062034c3e1c","multiton": true  })
            // this.videoAd1.onError(err => {
            //     console.log(err)
            //     console.log('广告金币创建出错')
            // })
            // this.videoAd2 = wx.createRewardedVideoAd({ adUnitId: "adunit-4d6ad9e44dbe8427","multiton": true  })
            // this.videoAd2.onError(err => {
            //     console.log(err)
            //     console.log('广告体力创建出错')
            // })
            // this.videoAd3 = wx.createRewardedVideoAd({ adUnitId: "adunit-48c6098d0b51f44f","multiton": true  })
            // this.videoAd3.onError(err => {
            //     console.log(err)
            //     console.log('广告幸运宝箱创建出错')
            // })
            // this.videoAd4 = wx.createRewardedVideoAd({ adUnitId: "adunit-005b802515865b0e","multiton": true  })
            // this.videoAd4.onError(err => {
            //     console.log(err)
            //     console.log('广告加时创建出错')
            // })
            // this.videoAd5 = wx.createRewardedVideoAd({ adUnitId: "adunit-cdd48e52da625ced","multiton": true  })
            // this.videoAd5.onError(err => {
            //     console.log(err)
            //     console.log('广告刷新创建出错')
            // })
            // this.videoAd6 = wx.createRewardedVideoAd({ adUnitId: "adunit-1df389b1fde36ce2","multiton": true  })
            // this.videoAd6.onError(err => {
            //     console.log(err)
            //     console.log('广告冻结创建出错')
            // })
            // this.videoAd7 = wx.createRewardedVideoAd({ adUnitId: "adunit-1af7d35d835bdf94","multiton": true  })
            // this.videoAd7.onError(err => {
            //     console.log(err)
            //     console.log('广告调色创建出错')
            // })
            // this.videoAd8 = wx.createRewardedVideoAd({ adUnitId: "adunit-77a0bc68e37ae34a","multiton": true  })
            // this.videoAd8.onError(err => {
            //     console.log(err)
            //     console.log('广告消除创建出错')
            // })
            // this.videoAd9 = wx.createRewardedVideoAd({ adUnitId: "adunit-73f18d53eec74320","multiton": true  })
            // this.videoAd9.onError(err => {
            //     console.log(err)
            //     console.log('广告存钱罐创建出错')
            // })
            // this.videoAd10 = wx.createRewardedVideoAd({ adUnitId: "adunit-488a6e06cd4925f3","multiton": true  })
            // this.videoAd10.onError(err => {
            //     console.log(err)
            //     console.log('广告幸运宝箱加速创建出错')
            // })
            // this.videoAd11 = wx.createRewardedVideoAd({ adUnitId: "adunit-670c20e813d6c824","multiton": true  })
            // this.videoAd11.onError(err => {
            //     console.log(err)
            //     console.log('广告结算星星创建出错')
            // })
            // this.videoAd12 = wx.createRewardedVideoAd({ adUnitId: "adunit-e66fae7bede06d25","multiton": true  })
            // this.videoAd12.onError(err => {
            //     console.log(err)
            //     console.log('广告宝箱双倍奖励创建出错')
            // })
            // this.videoAd13 = wx.createRewardedVideoAd({ adUnitId: "adunit-ba3d5b322d710a1c","multiton": true  })
            // this.videoAd13.onError(err => {
            //     console.log(err)
            //     console.log('广告免费礼物创建出错')
            // })
            // this.videoAd14 = wx.createRewardedVideoAd({ adUnitId: "adunit-b79881810f87bf39","multiton": true  })
            // this.videoAd14.onError(err => {
            //     console.log(err)
            //     console.log('广告开局-魔法棒创建出错')
            // })
            // this.videoAd15 = wx.createRewardedVideoAd({ adUnitId: "adunit-cde6a3434d80faa7","multiton": true  })
            // this.videoAd15.onError(err => {
            //     console.log(err)
            //     console.log('广告开局-双倍星星创建出错')
            // })
            // this.videoAd16 = wx.createRewardedVideoAd({ adUnitId: "adunit-f3ec18ec3ae2bf23","multiton": true  })
            // this.videoAd16.onError(err => {
            //     console.log(err)
            //     console.log('广告开局-加时创建出错')
            // })
            // this.videoAd17 = wx.createRewardedVideoAd({ adUnitId: "adunit-40962ea7024a50c2","multiton": true  })
            // this.videoAd17.onError(err => {
            //     console.log(err)
            //     console.log('广告签到-双倍领取奖励创建出错')
            // })
            // this.videoAd18 = wx.createRewardedVideoAd({ adUnitId: "adunit-22295cb952f53328","multiton": true  })
            // this.videoAd18.onError(err => {
            //     console.log(err)
            //     console.log('广告解锁花盆创建出错')
            // })
            // this.videoAd19 = wx.createRewardedVideoAd({ adUnitId: "adunit-664714572acefb2d","multiton": true  })
            // this.videoAd19.onError(err => {
            //     console.log(err)
            //     console.log('广告解锁花盆创建出错')
            // })
        }


        // // 横幅广告版本支持
        // // 竖屏需铺满宽度
        // if (this.compareVersion(this.sdkVersion, "2.0.4") >= 0) {
        //     this.BannerAd = wx.createBannerAd({
        //         adUnitId: "adunit-a2069969a71dde5a",
        //         adIntervals: 30,
        //         style: {
        //             left: 0,
        //             top: 0,
        //             width: 320
        //         }
        //     })

        //     this.BannerAd.onResize((size) => {
        //         this.BannerAdHight = size.height
        //         this.BannerAd.style.top = screenHeight - this.BannerAdHight
        //         this.BannerAd.style.left = (screenWidth - 320) / 2
        //     });

        //     this.BannerAd.onError((errMsg: string, errCode: number) => {
        //         // console.log(' banner 广告错误',err.errCode);
        //     })

        //     // 广告加载回调
        //     this.BannerAd.onLoad(() => {
        //         // console.log(' banner 广告加载回调');
        //     })
        // }

        // const customAdHome = wx.createCustomAd({
        //     adUnitId: 'adunit-c83f8f6c0ae8f2fb',
        //     style: {
        //         left: screenWidth - 65,
        //         top: 60,
        //     }
        // })

        // const customAdBanner = wx.createCustomAd({
        //     adUnitId: 'adunit-6875c84b8eeecc7f',
        //     style: {
        //         top: screenHeight - 95,
        //         left: screenWidth / 7,

        //     }
        // })

        // this.customAdMap.set("home", customAdHome)
        // this.customAdMap.set("banner", customAdBanner)
    }
    createRewardedVideoAd(adId,type:string){
        this.videoAd = wx.createRewardedVideoAd({ adUnitId: adId,"multiton": true  })
        this.videoAd.load()
        this.videoAd.onError(err => {
            console.log(err)
            console.log(`广告${type}创建出错`,adId)
        })
       return  this.videoAd
    }
    

    login?(args?: any, callback?: Function) {
        if (callback) {
            callback();
        }
    }
    pay?(args?: any, callback?: Function) {
        if (callback) {
            callback();
        }
    }
    share(args?: any, callback?: Function) {
        let pre = "https://i.postimg.cc/xdW0hfJY/20241021172111.jpg"
        // let titleArr = [];
        // let ind = Math.floor(Math.random() * 3);
        wx.shareAppMessage({
            title: "不花钱只烧脑，你能过这一关吗?",
            desc: "",
            imageUrl: pre,
            query: "",
            success() {
            },
            fail(e) {
            },
        });

        setTimeout(() => {
            if (callback) {
                callback();
            }
        }, 3500)
    }
    showBanner(stub?: any, callback?: Function) {

        let ran = Math.floor(Math.random() * 2)
        if (ran == 0) {
            if (this.BannerAd == null) {
                return
            }
            this.BannerAd.show().then(() => {
                //console.log('banner广告展示完成');

            }).catch((err) => {
                // console.log('banner广告展示失败', JSON.stringify(err));
            })
        } else {
            this.showBlockAd("banner")
        }
        if (callback) {
            callback()
        }
    }

    hideBanner(args?: any, callback?: Function) {
        if (args === 1) {
            return
        }
        if (this.BannerAd != null) {
            this.BannerAd.hide()
        }
        this.hideBlockAd("banner")
    }



    showInsertAd(args?: any, callback?: Function, stub?: any) {
        //插屏版本支持
        if (this.compareVersion(this.sdkVersion, "2.6.0") >= 0) {
            const interstitialAd = wx.createInterstitialAd({
                adUnitId: "adunit-bac1963dd0b34549"
            }
            );
            interstitialAd.onLoad(() => {
                //interstitialAd.show().catch((err) => { console.log(err); })
                interstitialAd.show().then(() => {
                    console.log('插屏广告展示完成');
                    if (callback) {
                        callback()
                    }
                }).catch((err) => {
                    console.log('插屏广告展示失败', JSON.stringify(err));
                })
            });
            // interstitialAd.load()

            let closeFun = () => {
                interstitialAd.offClose(closeFun)
                interstitialAd.destroy()
            }

            interstitialAd.onClose(closeFun)


            interstitialAd.onError(err => {
                console.log("插屏广告加载失败", err);
                interstitialAd.offError()
            });

            interstitialAd.onLoad(err => {
                console.log("插屏广告onLoad失败", err);
                interstitialAd.offLoad()
            });


        }

    }


    showVideoAd(args?: any, callback?: Function, errorCB?: Function) {
        let videoAd = null
        // switch (args) {
        //     case ADType.GOLD:
        //         videoAd = this.videoAd1
        //         break;
        //     case ADType.HP:
        //         videoAd = this.videoAd2
        //         break;
        //     case ADType.FREEBOX:
        //         videoAd = this.videoAd3
        //         break;
        //     case ADType.ADDTIME:
        //         videoAd = this.videoAd4
        //         break;
        //     case ADType.REF:
        //         videoAd = this.videoAd5
        //         break;
        //     case ADType.SPENCE:
        //         videoAd = this.videoAd6
        //         break;
        //     case ADType.TIAOSE:
        //         videoAd = this.videoAd7
        //         break;
        //     case ADType.CLEAR:
        //         videoAd = this.videoAd8
        //         break;
        //     case ADType.MONEYBOX:
        //         videoAd = this.videoAd9
        //         break;
        //     case ADType.FREEBOXCLOCK:
        //         videoAd = this.videoAd10
        //         break;
        //     case ADType.DOUBLETY:
        //         videoAd = this.videoAd11
        //         break;
        //     case ADType.DOUBLEBOX:
        //         videoAd = this.videoAd12
        //         break;
        //     case ADType.ALL:
        //         videoAd = this.videoAd13
        //         break;
        //     case ADType.MAGIC:
        //         videoAd = this.videoAd14
        //         break;
        //     case ADType.DOUBLEXX:
        //         videoAd = this.videoAd15
        //         break;
        //     case ADType.ONTIME:
        //         videoAd = this.videoAd16
        //         break;
        //     case ADType.DOUBLESIGN:
        //         videoAd = this.videoAd17
        //         break;
        //     case ADType.UNCLOCKPOT:
        //         videoAd = this.videoAd18
        //         break;
        //     case ADType.UNCLOCKFROST:
        //         videoAd = this.videoAd19
        //         break;

        //     default:
        //         videoAd = this.videoAd19
        //         break;
        // }
        videoAd = this.defaultAd
        let wxVideoAd = this.createRewardedVideoAd(videoAd,args)
        if (!wxVideoAd) {
            console.log("暂无广告位")
            if (callback) {
                callback();
            }
            return;
        }
        wxVideoAd.show()
            .then()
            .catch(err => {
                console.log(err.errMsg)
                wxVideoAd.load().then(() => wxVideoAd.show())

            })

        let closeFun = (res) => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined

            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                if (callback) {
                    callback()
                    wxVideoAd.destroy()
                }
            } else {
                if (errorCB) {
                    errorCB()
                }
            }
            
            wxVideoAd.load()
            try{
                wxVideoAd.offClose(closeFun)
            }catch{
            }
            wxVideoAd.destroy()
        }
        wxVideoAd.onClose(closeFun)
    }
    otherFun(args?: any, callback?: Function) {
        if (callback) {
            callback();
        }
    }
    shark(args?: any, callback?: Function) {
        if (args == 1) {
            wx.vibrateLong(
                {
                    success: () => {
                        // wx.showToast({
                        //     title: '震动成功',
                        // })
                    },
                    fail: (errMsg) => {
                        // wx.showToast({
                        //     title: `震动失败：${errMsg}`,
                        // })
                    },
                }
            );
        }
        else {

            wx.vibrateShort(
                {
                    type: "light",
                    success: () => {
                        // wx.showToast({
                        //     title: '震动成功',
                        // })
                    },
                    fail: (errMsg) => {
                        // wx.showToast({
                        //     title: `震动失败：${errMsg}`,
                        // })
                    },
                }
            );
        }
    }
    recordVideo?(args?: any, callback?: Function) {
        if (callback) {
            callback();
        }
    }
    shareVideo?(args?: any, callback?: Function) {
        if (callback) {
            callback();
        }
    }
    stopRecorderManager?(args?: any, callback?: Function) {
        if (callback) {
            callback("test.png");
        }
    }
    setLanguage?(args?: any, callback?: Function): string {
        if (callback) {
            callback();
        }
        return "zh"
    }
    compareVersion(v1, v2): number {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }

    addCollect(callback?: Function) {
        if (callback) {
            callback(true);
        }
    }

    addDesktop(callback?: Function) {
        if (callback) {
            callback(true);
        }
    }

    reportEvent(eventId: string, data: object) {
        wx.reportEvent(eventId, data);
    }
   
}